﻿using ProjectCloth.Entity;
using ProjectCloth.Entity.Enum;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class GeneralExpensesFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        public GeneralExpensesFrm()
        {
            InitializeComponent();

            var acountList = db.CashAccounts.ToList();
            //companyCbb.DataSource = db.Companies.ToList();
            //companyCbb.ValueMember = "Id";
            //companyCbb.DisplayMember = "Name";
            outmoneycbb.DataSource = acountList;
            outmoneycbb.ValueMember = "Id";
            outmoneycbb.DisplayMember = "TradeTypeName";
            outmoneycbb.SelectedValue = 0;
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.ValueMember = "Id";
            makerCbx.DisplayMember = "Name";
            var subjectColums = dataGridView1.Columns["subjectName"];
            var comb = new DataGridViewComboEditBoxColumn();
            if (subjectColums != null)
            {
                comb.DefaultCellStyle.NullValue = "";// lbType.Text;//显示默认值 根据自己的需求改
                comb.DataPropertyName = "";
                comb = subjectColums as DataGridViewComboEditBoxColumn;
                comb.DataSource = db.Subjects.ToList();
                comb.ValueMember = "Id";
                comb.DisplayMember = "Name";

            }
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            int accountId = 0;
            var account = new CashAccount();
            if (outmoneycbb.SelectedValue == null || (int)outmoneycbb.SelectedValue <= 0)
            {
                MessageBox.Show("请选择付款账号！");
                return;
            }
            else
            {
                accountId = (int)outmoneycbb.SelectedValue;
                account = db.CashAccounts.Find(accountId);
            }
            try
            {


                var generalExp = new GeneralExpenses()
                {
                    CompanyName = companyTxt.Text,
                    CreateTime = DateTime.Now,
                    CreatorId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                    MakerId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                    MakerName = makerCbx.Text != null ? makerCbx.Text : "",
                    Summary=summaryTxt.Text,
                    Remark=RemarkTxt.Text,
                    //MakeTime = outmoneyTime.Value,
                    PayAccountId = outmoneycbb.SelectedValue != null ? (int)outmoneycbb.SelectedValue : 0,
                    PayAmount = outmoneyAmountTxt.Text != null ? Convert.ToDecimal(outmoneyAmountTxt.Text) : 0,
                    PayAccountName = !string.IsNullOrEmpty(outmoneycbb.Text) ? outmoneycbb.Text : ""
                    //GeneralExpensesNo= dataGridView1.Columns["subjectName"].
                };
                var generalexp = db.GeneralExpenseses.Add(generalExp);
                var result = db.SaveChanges();
                if (result > 0)
                {
                    List<GeneralExpensesItem> list = new List<GeneralExpensesItem>();
                    for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                    {
                        if (dataGridView1.Rows[i].Cells["subjectName"] != null && dataGridView1.Rows[i].Cells["subjectName"].Value != null)
                        {
                            var item = new GeneralExpensesItem()
                            {
                                SubjectId = (int)dataGridView1.Rows[i].Cells["subjectName"].Value,
                                SubjectName = dataGridView1.Rows[i].Cells["subjectName"].EditedFormattedValue.ToString(),
                                GeneralExpensesId = generalexp.Id,
                                Cost = (dataGridView1.Rows[i].Cells["Amount"] != null && dataGridView1.Rows[i].Cells["Amount"].Value != null) ? Convert.ToDecimal(dataGridView1.Rows[i].Cells["Amount"].Value) : 0,
                                Remark = dataGridView1.Rows[i].Cells["Remark"].Value != null ? dataGridView1.Rows[i].Cells["Remark"].Value.ToString() : "",

                            };
                            list.Add(item);
                        }
                    }
                    db.GeneralExpensesItems.AddRange(list);
                    var rs = db.SaveChanges();
                    if (rs > 0)
                    {
                        var oldAmount = account.Amount;
                        account.OriginalAmount = oldAmount;
                        account.Amount -= generalExp.PayAmount;
                        account.UpdateTime = DateTime.Now;
                        var log = new CashAccountLog()
                        {
                            CashAccountId = account.Id,
                            CreateTime = DateTime.Now,
                            CurrentAmount = account.Amount,
                            OriginalAmount = oldAmount,
                            Remark = RemarkTxt.Text,
                            MakerId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                            MakerTime = outmoneyTime.Value,
                            RelatedObject = companyTxt.Text,
                            Source = "一般费用",
                            VariableAmount = -generalExp.PayAmount,
                            LoginId = LoginInfo.GetLoginInfo().UserId,
                        };
                        db.CashAccountLogs.Add(log);
                        db.SaveChanges();
                        MessageBox.Show("保存成功！");
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("保存失败！");
            }
            #region reset
            dataGridView1.Rows.Clear();
            outmoneyAmountTxt.Text = "";
            #endregion
        }
        //改变键盘键enter效果
        #region
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            base.ProcessCmdKey(ref msg, keyData);
            var dgv = dataGridView1;
            TextBox salesum = (TextBox)this.Controls.Find("outmoneyAmountTxt", true)[0];
            bool _disable = false;

            switch (keyData)
            {
                case Keys.Enter:
                    if (dgv.CurrentRow != null)
                    {
                        if (dgv.CurrentRow.Cells["subjectName"] != null)
                        {
                            var dropDown = dgv.CurrentRow.Cells["subjectName"];
                            var sel = dropDown.Selected;
                            var display = dropDown.EditedFormattedValue.ToString();
                            if (display == "")
                            {
                                break;
                            }
                            var subjectno = dropDown.EditedFormattedValue.ToString();//Convert.ToInt32(dataGridView1.CurrentRow.Cells["ProductNo"].Value);

                            var subject = db.Subjects.Where(o => o.Name.Contains(subjectno) || o.ShortName.Contains(subjectno)).FirstOrDefault();
                            var index = dgv.CurrentRow.Index;
                            if (index >= 0)
                            {
                                //if (dgv.Rows[index - 0].Cells["Amount"].Selected == true)
                                {
                                    decimal paysum = 0;
                                    for (int i = 0; i < dgv.RowCount - 1; i++)
                                    {
                                        paysum += Convert.ToDecimal(dgv.Rows[i].Cells["Amount"].Value);
                                    }
                                    salesum.Text = paysum.ToString();

                                }

                            }

                        }
                        SendKeys.Send("{Tab}");
                    }

                    _disable = true;
                    break;
                case Keys.F12:
                    {
                        //var index = dgv.CurrentRow.Index;
                        //if (index > 0)
                        //{
                        //    if (dgv.Rows[index - 1].Cells["Sum"].Selected == true)
                        //    {
                        //        decimal paysum = 0;
                        //        for (int i = 0; i < dgv.RowCount - 1; i++)
                        //        {
                        //            paysum += Convert.ToDecimal(dgv.Rows[i].Cells["Sum"].Value);
                        //        }
                        //        salesum.Text = paysum.ToString();

                        //    }

                        //}
                        _disable = true;
                        break;
                    }
                default:
                    break;
            }

            return _disable;
        }
        #endregion
    }
}
